//
//  JSQAudioPlaybackAnimation.m
//  Conversation
//
//  Created by C_HAO on 15/9/30.
//  Copyright © 2015年 CHAOO. All rights reserved.
//

#import "JSQAudioPlaybackAnimation.h"
#import "JSQMessageTools.h"

@interface JSQAudioPlaybackAnimation ()

@property(nonatomic, retain) AFSoundPlayback *soundPlayback;

@property(nonatomic, retain) AFSoundItem *soundItem;

@property(nonatomic, retain) JSQMessagesCollectionViewVoiceCell *viewVoiceCell;


@end

@implementation JSQAudioPlaybackAnimation

+ (JSQAudioPlaybackAnimation *)shareAudioPlaybackAnimation {
    static JSQAudioPlaybackAnimation *audioPlaybackAnimation;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        audioPlaybackAnimation = [[self alloc] init];
    });
    return audioPlaybackAnimation;
}

- (void)playFilePath:(NSURL *)filePath animation:(JSQMessagesCollectionViewVoiceCell *)animation {
    _soundPlayback = [AFSoundPlayback shareSoundPlay];
    [_viewVoiceCell stopVoiceAnimation];
    _viewVoiceCell = animation;
    [_viewVoiceCell playVoiceAnimation];
    if (_soundPlayback.status == AFSoundStatusPlaying) {
        if ([filePath.absoluteString isEqualToString:_soundPlayback.currentItem.URL.absoluteString]) {
            [_soundPlayback restart];
        } else {
            __weak typeof(self) VC = self;
            [_soundPlayback listenFeedbackUpdatesWithBlock:^(AFSoundItem *item) {
                [VC.viewVoiceCell playVoiceAnimation];
            } andFinishedBlock:^{
                [VC.viewVoiceCell stopVoiceAnimation];
            }];
            [_soundPlayback pause];
        }
    }
    NSString *absoluteString = [filePath.absoluteString stringByReplacingOccurrencesOfString:@"file://" withString:@""];
    absoluteString = [JSQMessageTools audioFilePath:absoluteString];
    _soundItem = [[AFSoundItem alloc] initWithLocalURL:[NSURL fileURLWithPath:absoluteString]];
    __weak typeof(self) VC = self;
    [_soundPlayback listenFeedbackUpdatesWithBlock:nil andFinishedBlock:^{
        [VC.viewVoiceCell stopVoiceAnimation];
    }];
    [_soundPlayback playSound:_soundItem];
}

- (void)stop {
    [_viewVoiceCell stopVoiceAnimation];
    [_soundPlayback pause];
}

@end
